//
//  Post.swift
//  YitArtApp
//
//  Created by 千云锋 on 2021/11/5.
//

import SwiftUI


struct PostList: Codable {
    var list: [Post]
}

struct Post: Codable, Identifiable {
    let id: Int
    let avatar: String // 头像，图片名称
    let vip: Bool // 是否是vip
    let name: String // 昵称
    let date: String
    var isFollowed: Bool
    
    let text: String
    let images: [String]
    
    let commentCount: Int
    let likeCount: Int
    let isLiked: Bool
    
    
}

extension Post {
    var avatarImage: Image {
        return loadImage(name: avatar)
    }
    
    var commentCountText: String {
        if commentCount <= 0 {return "评论"}
        if commentCount < 1000 {return "\(commentCount)"}
        return String(format: "%.1f", Double(commentCount)/1000)
    }
    
    var likeCountText: String {
        if likeCount <= 0 {return "点赞"}
        if likeCount < 1000 {return "\(likeCount)"}
        return String(format: "%.1f", Double(likeCount)/1000)
    }
}

let postList = loadPostListData("PostListData_recommend_1.json")
func loadPostListData(_ fileName: String) -> PostList {
    guard let url = Bundle.main.url(forResource: fileName, withExtension: nil) else {
        fatalError("无法找到\(fileName)文件")
    }
    guard let data = try? Data(contentsOf: url) else {
        fatalError("无法加载\(url)")
    }
    guard let list = try? JSONDecoder().decode(PostList.self, from: data) else {
        fatalError("无法解析PostList")
    }
    return list
    
}

func loadImage(name: String) -> Image {
    return Image(uiImage: UIImage(named: name)!)
}
